﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FrameController : MonoBehaviour
{
    public FrameAnimation[] Animations;

    public int frameRate = 10;
    public string Enter = "idle";
    public float delayTimeRange = 1f;

    private readonly Dictionary<string, FrameState> dict = new();
    private FrameState currState;
    private SpriteRenderer render;

    public void Awake()
    {
        render = GetComponent<SpriteRenderer>();

        for (int i = 0; i < Animations.Length; i++)
        {
            var anim = Animations[i];
            if (dict.ContainsKey(anim.Name))
            {
                throw new Exception($"FrameAnimation,动作名称不能重名");
            }
            var frameState = new FrameState();
            frameState.anim = anim;
            frameState.frameRate = frameRate;
            frameState.render = render;
            dict[anim.Name] = frameState;
        }

        StartCoroutine(Delay());
    }

    public void Update()
    {
        if (currState == null)
        {
            return;
        }

        currState.Update();
    }

    IEnumerator Delay()
    {
        var delayTime = UnityEngine.Random.Range(0,delayTimeRange);
        yield return new WaitForSeconds(delayTime);
        Play(Enter);
    }

    public bool Contains(string anim_name)
    {
        return dict.ContainsKey(anim_name);
    }

    public void Play(string anim_name)
    {
        if (!Contains(anim_name))
        {
            return;
        }

        if (currState != null)
        {
            currState.Stop();
        }
        currState = dict[anim_name];
        currState.Start();
    }
}
